package web.get;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.Book;
import domain.User;
import util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/getBook")
public class GetBookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        Map<String,Object> msg = new HashMap<>(8);
        String bid = request.getParameter("bid");
        User user = ServletUtil.checkLogin(request);
        Book book=null;
        try{
            book = ServletUtil.checkBook(user, Integer.parseInt(bid));
        }catch (Exception e){
            e.printStackTrace();
        }
        if(book==null){
            msg.put("msg","失败");
            msg.put("isSuccess",false);
        }else {
            msg.put("msg","成功");
            msg.put("isSuccess",true);
        }
        msg.put("book",book);
        new ObjectMapper().writeValue(response.getOutputStream(),msg);

    }
}
